
const pool  = require('../config/db');
const bcrypt = require('bcrypt');

const userService = {
  // 注册用户
  register: async (user) => {
    try {
      const { username, password, nickname = null, email } = user || {};
      // 注册新用户
      const sql = 'INSERT INTO user (username, password_hash, nickname, email) VALUES (?,?,?,?)';
      const [result] = await pool.execute(sql, [username, password, nickname, email]);
      if (result.affectedRows > 0) {
        return {};
      }else{
        const error = new Error('注册失败');
        error.statusCode = 400;
        throw error;
      }
    } catch (error) {
      throw error;
    }
  },

  // 登录用户
  login: async (user) => {
    try {
      const { username, password } = user;
      const sql = 'SELECT * FROM user WHERE username = ?';
      const [result] = await pool.execute(sql, [username]);
      if (result.length === 0) {
        throw new Error('用户名或密码错误');
      }
      // 比较用户的密码 与 数据库中的密码是否一致
      const isPasswordValid = await bcrypt.compare(password, result[0].password_hash);
      if (!isPasswordValid) {
        throw new Error('用户名或密码错误');
      }

      return {
        userId: result[0].id,
        username: result[0].username,
        nickname: result[0].nickname,
        email: result[0].email
      };
    } catch (error) {
      throw error;
    }
  },

  // 获取用户信息
  getUserById: async (id) => {
    try{
      const sql = `select * from user where id = ?`;
      const [ rows ] = await pool.execute(sql, [id]);
      return rows;
    }catch(err){
      console.log(err);
      throw err; // 抛给控制器处理
    }
  },

  // 更新用户信息
  updateUser: async (user) => { 
    try{
      const sql = `update user set username = ?, email = ? where id = ?`;
      const [ rows ] = await pool.execute(sql, [user.name, user.email, user.id]);
      if(rows?.affectedRows > 0){
        return {
          userId: rows.insertId,
          username: user?.name,
          email: user?.email
        };
      }
    }catch(err){
      console.log(err);
      throw err; // 抛给控制器处理
    }
  },

  deleteUser: async (user) => {
    try{
      const sql = `delete from user where id = ?`;
      const [ rows ] = await pool.execute(sql, [user.id]);
      if(rows?.affectedRows > 0){
        return {};
      }
    }catch(err){
      throw err; // 抛给控制器处理
    }
  },

  getUserList: async () => {
    try {
      const sql = 'SELECT * FROM user';
      const [result] = await pool.execute(sql);
      return result;
    } catch (error) {
      throw error;
    }
  },

  // 根据用户名判断用户是否存在
  checkUserExists: async (username) => {
    try {
      const sql = 'SELECT * FROM user WHERE username = ?';
      const [result] = await pool.execute(sql, [username]);
      return result.length > 0;
    } catch (error) {
      throw error;
    }
  },
  
  // 根据email判断用户是否存在
  checkEmailExists: async (email) => {
    try {
      const sql = 'SELECT * FROM user WHERE email = ?';
      const [result] = await pool.execute(sql, [email]);
      return result.length > 0;
    } catch (error) {
      throw error;
    }
  },
}

module.exports = userService